<template>
    <view class="container">
        <!-- 页面标题 -->
        <view class="page-header">
            <view class="title-section">
                <text class="page-title">新增客户</text>
                <text class="page-subtitle">填写客户基本信息</text>
            </view>
        </view>
        
        <!-- 表单容器 -->
        <view class="form-container">
            <!-- 表单步骤导航 -->
            <view class="form-steps">
                <view class="step-item" :class="{ 'active': currentStep === 1 }">
                    <view class="step-number">1</view>
                    <view class="step-text">基本信息</view>
                </view>
                <view class="step-line" :class="{ 'active': currentStep >= 2 }"></view>
                <view class="step-item" :class="{ 'active': currentStep === 2 }">
                    <view class="step-number">2</view>
                    <view class="step-text">证件信息</view>
                </view>
                <view class="step-line" :class="{ 'active': currentStep >= 3 }"></view>
                <view class="step-item" :class="{ 'active': currentStep === 3 }">
                    <view class="step-number">3</view>
                    <view class="step-text">合同信息</view>
                </view>
            </view>
            
            <!-- 步骤1：基本信息 -->
            <view class="form-step" v-if="currentStep === 1">
                <view class="form-group">
                    <view class="form-label">客户名称 <text class="required">*</text></view>
                    <view class="form-input-wrapper">
                        <input type="text" v-model="customer.name" placeholder="请输入客户名称" @blur="validateField('name')" />
                        <view class="error-message" v-if="errors.name">{{ errors.name }}</view>
                    </view>
                </view>
                
                <view class="form-group">
                    <view class="form-label">联系人姓名 <text class="required">*</text></view>
                    <view class="form-input-wrapper">
                        <input type="text" v-model="customer.contactPerson" placeholder="请输入联系人姓名" @blur="validateField('contactPerson')" />
                        <view class="error-message" v-if="errors.contactPerson">{{ errors.contactPerson }}</view>
                    </view>
                </view>
                
                <view class="form-group">
                    <view class="form-label">联系电话 <text class="required">*</text></view>
                    <view class="form-input-wrapper">
                        <input type="tel" v-model="customer.phone" placeholder="请输入联系电话" @blur="validateField('phone')" />
                        <view class="error-message" v-if="errors.phone">{{ errors.phone }}</view>
                    </view>
                </view>
                
                <view class="form-group">
                    <view class="form-label">客户类型</view>
                    <view class="form-radio-group">
                        <radio-group v-model="customer.type">
                            <label class="radio-item" v-for="(item, index) in customerTypes" :key="index">
                                <radio :value="item.value" />
                                <text>{{ item.label }}</text>
                            </label>
                        </radio-group>
                    </view>
                </view>
                
                <view class="form-group">
                    <view class="form-label">适用费率套餐 <text class="required">*</text></view>
                    <view class="form-input-wrapper">
                        <picker :range="packageOptions" :range-key="'name'" v-model="customer.packageIndex" @change="onPackageChange">
                            <view class="picker">
                                {{ customer.packageName || '请选择套餐' }}
                            </view>
                        </picker>
                        <view class="error-message" v-if="errors.packageName">{{ errors.packageName }}</view>
                    </view>
                </view>
                
                <view class="form-group">
                    <view class="form-label">备注信息</view>
                    <view class="form-input-wrapper">
                        <textarea v-model="customer.remark" placeholder="请输入备注信息" maxlength="500"></textarea>
                    </view>
                </view>
            </view>
            
            <!-- 步骤2：证件信息 -->
            <view class="form-step" v-if="currentStep === 2">
                <view class="form-group">
                    <view class="form-label">证件类型</view>
                    <view class="form-radio-group">
                        <radio-group v-model="customer.idType">
                            <label class="radio-item" v-for="(item, index) in idTypes" :key="index">
                                <radio :value="item.value" />
                                <text>{{ item.label }}</text>
                            </label>
                        </radio-group>
                    </view>
                </view>
                
                <view class="form-group">
                    <view class="form-label">证件号码 <text class="required">*</text></view>
                    <view class="form-input-wrapper">
                        <input type="text" v-model="customer.idNumber" placeholder="请输入证件号码" @blur="validateField('idNumber')" />
                        <view class="error-message" v-if="errors.idNumber">{{ errors.idNumber }}</view>
                    </view>
                </view>
                
                <view class="form-group">
                    <view class="form-label">证件照片 <text class="required">*</text></view>
                    <view class="form-input-wrapper">
                        <view class="upload-container">
                            <view class="upload-item" v-for="(image, index) in customer.idImages" :key="index">
                                <image :src="image" mode="aspectFill" class="upload-preview"></image>
                                <view class="upload-delete" @click="removeIdImage(index)">×</view>
                            </view>
                            <view class="upload-btn" @click="chooseIdImage" v-if="customer.idImages.length < maxIdImages">
                                <view class="upload-icon">+</view>
                                <view class="upload-text">上传证件照片</view>
                            </view>
                        </view>
                        <view class="upload-tip">请上传证件正反面照片（最多2张）</view>
                        <view class="error-message" v-if="errors.idImages">{{ errors.idImages }}</view>
                    </view>
                </view>
            </view>
            
            <!-- 步骤3：合同信息 -->
            <view class="form-step" v-if="currentStep === 3">
                <view class="form-group">
                    <view class="form-label">合同编号 <text class="required">*</text></view>
                    <view class="form-input-wrapper">
                        <input type="text" v-model="customer.contractNumber" placeholder="请输入合同编号" @blur="validateField('contractNumber')" />
                        <view class="error-message" v-if="errors.contractNumber">{{ errors.contractNumber }}</view>
                    </view>
                </view>
                
                <view class="form-group">
                    <view class="form-label">合同有效期 <text class="required">*</text></view>
                    <view class="form-input-wrapper">
                        <picker mode="date" :value="customer.contractStartDate" start="2020-01-01" end="2030-12-31" @change="onContractStartDateChange">
                            <view class="picker">
                                {{ customer.contractStartDate || '开始日期' }}
                            </view>
                        </picker>
                        <view class="date-separator">-</view>
                        <picker mode="date" :value="customer.contractEndDate" start="2020-01-01" end="2030-12-31" @change="onContractEndDateChange">
                            <view class="picker">
                                {{ customer.contractEndDate || '结束日期' }}
                            </view>
                        </picker>
                    </view>
                    <view class="error-message" v-if="errors.contractPeriod">{{ errors.contractPeriod }}</view>
                </view>
                
                <view class="form-group">
                    <view class="form-label">合同照片 <text class="required">*</text></view>
                    <view class="form-input-wrapper">
                        <view class="upload-container">
                            <view class="upload-item" v-for="(image, index) in customer.contractImages" :key="index">
                                <image :src="image" mode="aspectFill" class="upload-preview"></image>
                                <view class="upload-delete" @click="removeContractImage(index)">×</view>
                            </view>
                            <view class="upload-btn" @click="chooseContractImage" v-if="customer.contractImages.length < maxContractImages">
                                <view class="upload-icon">+</view>
                                <view class="upload-text">上传合同照片</view>
                            </view>
                        </view>
                        <view class="upload-tip">请上传合同照片（最多5张）</view>
                        <view class="error-message" v-if="errors.contractImages">{{ errors.contractImages }}</view>
                    </view>
                </view>
                
                <view class="form-group">
                    <view class="form-label">创建人</view>
                    <view class="form-input-wrapper">
                        <input type="text" v-model="customer.creator" placeholder="自动填充" disabled />
                    </view>
                </view>
            </view>
        </view>
        
        <!-- 操作按钮 -->
        <view class="action-buttons">
            <button class="back-btn" @click="goBack" v-if="currentStep > 1">
                <i class="fa fa-arrow-left"></i>
                <text>上一步</text>
            </button>
            <button class="next-btn" @click="nextStep" v-if="currentStep < 3">
                <text>下一步</text>
                <i class="fa fa-arrow-right"></i>
            </button>
            <button class="submit-btn" @click="submitForm" v-if="currentStep === 3">
                <text>提交</text>
                <i class="fa fa-check"></i>
            </button>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            currentStep: 1,
            maxIdImages: 2,
            maxContractImages: 5,
            customer: {
                name: '',
                contactPerson: '',
                phone: '',
                type: 'company', // 默认企业客户
                packageIndex: 0,
                packageName: '',
                remark: '',
                idType: 'business_license', // 默认营业执照
                idNumber: '',
                idImages: [],
                contractNumber: '',
                contractStartDate: '',
                contractEndDate: '',
                contractImages: [],
                creator: '管理员' // 实际项目中应从登录状态获取
            },
            customerTypes: [
                { label: '企业客户', value: 'company' },
                { label: '个人客户', value: 'individual' }
            ],
            idTypes: [
                { label: '营业执照', value: 'business_license' },
                { label: '身份证', value: 'id_card' },
                { label: '组织机构代码证', value: 'organization_code' },
                { label: '税务登记证', value: 'tax_registration' }
            ],
            packageOptions: [
                { id: 1, name: '基础套餐', description: '基础功能服务' },
                { id: 2, name: '高级套餐', description: '包含高级分析功能' },
                { id: 3, name: '尊享套餐', description: '全方位定制服务' }
            ],
            errors: {} // 表单验证错误信息
        }
    },
    onLoad() {
        // 初始化数据
        this.initData();
    },
    methods: {
        // 初始化数据
        initData() {
            // 实际项目中可以从登录状态获取创建人信息
            this.customer.creator = uni.getStorageSync('userInfo')?.username || '管理员';
        },
        
        // 表单字段验证
        validateField(field) {
            const value = this.customer[field];
            
            switch(field) {
                case 'name':
                    if (!value) {
                        this.errors.name = '请输入客户名称';
                    } else {
                        delete this.errors.name;
                    }
                    break;
                    
                case 'contactPerson':
                    if (!value) {
                        this.errors.contactPerson = '请输入联系人姓名';
                    } else {
                        delete this.errors.contactPerson;
                    }
                    break;
                    
                case 'phone':
                    const phoneReg = /^1[3-9]\d{9}$/;
                    if (!value) {
                        this.errors.phone = '请输入联系电话';
                    } else if (!phoneReg.test(value)) {
                        this.errors.phone = '请输入有效的手机号码';
                    } else {
                        delete this.errors.phone;
                    }
                    break;
                    
                case 'idNumber':
                    if (!value) {
                        this.errors.idNumber = '请输入证件号码';
                    } else {
                        // 根据证件类型进行不同的验证
                        if (this.customer.idType === 'id_card') {
                            const idCardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
                            if (!idCardReg.test(value)) {
                                this.errors.idNumber = '请输入有效的身份证号码';
                            } else {
                                delete this.errors.idNumber;
                            }
                        } else {
                            delete this.errors.idNumber;
                        }
                    }
                    break;
                    
                case 'contractNumber':
                    if (!value) {
                        this.errors.contractNumber = '请输入合同编号';
                    } else {
                        delete this.errors.contractNumber;
                    }
                    break;
            }
        },
        
        // 验证当前步骤的所有字段
        validateCurrentStep() {
            let isValid = true;
            
            if (this.currentStep === 1) {
                // 验证基本信息
                this.validateField('name');
                this.validateField('contactPerson');
                this.validateField('phone');
                
                if (!this.customer.packageName) {
                    this.errors.packageName = '请选择适用费率套餐';
                    isValid = false;
                } else {
                    delete this.errors.packageName;
                }
                
                if (this.errors.name || this.errors.contactPerson || this.errors.phone || this.errors.packageName) {
                    isValid = false;
                }
            } else if (this.currentStep === 2) {
                // 验证证件信息
                this.validateField('idNumber');
                
                if (this.customer.idImages.length === 0) {
                    this.errors.idImages = '请上传证件照片';
                    isValid = false;
                } else {
                    delete this.errors.idImages;
                }
                
                if (this.errors.idNumber || this.errors.idImages) {
                    isValid = false;
                }
            } else if (this.currentStep === 3) {
                // 验证合同信息
                this.validateField('contractNumber');
                
                if (!this.customer.contractStartDate || !this.customer.contractEndDate) {
                    this.errors.contractPeriod = '请选择完整的合同有效期';
                    isValid = false;
                } else if (this.customer.contractStartDate >= this.customer.contractEndDate) {
                    this.errors.contractPeriod = '合同结束日期必须晚于开始日期';
                    isValid = false;
                } else {
                    delete this.errors.contractPeriod;
                }
                
                if (this.customer.contractImages.length === 0) {
                    this.errors.contractImages = '请上传合同照片';
                    isValid = false;
                } else {
                    delete this.errors.contractImages;
                }
                
                if (this.errors.contractNumber || this.errors.contractPeriod || this.errors.contractImages) {
                    isValid = false;
                }
            }
            
            return isValid;
        },
        
        // 下一步
        nextStep() {
            if (this.validateCurrentStep()) {
                this.currentStep++;
            } else {
                // 滚动到第一个错误字段
                const firstErrorField = Object.keys(this.errors)[0];
                if (firstErrorField) {
                    uni.createSelectorQuery().select(`.error-message`).boundingClientRect(rect => {
                        if (rect) {
                            uni.pageScrollTo({
                                scrollTop: rect.top - 100,
                                duration: 300
                            });
                        }
                    }).exec();
                }
            }
        },
        
        // 上一步
        goBack() {
            if (this.currentStep > 1) {
                this.currentStep--;
            } else {
                uni.navigateBack();
            }
        },
        
        // 套餐选择变更
        onPackageChange(e) {
            const index = e.detail.value;
            this.customer.packageIndex = index;
            if (index > 0) {
                this.customer.packageName = this.packageOptions[index].name;
                delete this.errors.packageName;
            } else {
                this.customer.packageName = '';
            }
        },
        
        // 合同开始日期变更
        onContractStartDateChange(e) {
            this.customer.contractStartDate = e.detail.value;
            
            // 如果结束日期早于开始日期，重置结束日期
            if (this.customer.contractEndDate && this.customer.contractEndDate < this.customer.contractStartDate) {
                this.customer.contractEndDate = '';
            }
        },
        
        // 合同结束日期变更
        onContractEndDateChange(e) {
            this.customer.contractEndDate = e.detail.value;
        },
        
        // 选择证件照片
        chooseIdImage() {
            uni.chooseImage({
                count: this.maxIdImages - this.customer.idImages.length,
                sizeType: ['compressed'],
                sourceType: ['album', 'camera'],
                success: (res) => {
                    this.customer.idImages = [...this.customer.idImages, ...res.tempFilePaths];
                    if (this.customer.idImages.length > 0) {
                        delete this.errors.idImages;
                    }
                }
            });
        },
        
        // 移除证件照片
        removeIdImage(index) {
            this.customer.idImages.splice(index, 1);
        },
        
        // 选择合同照片
        chooseContractImage() {
            uni.chooseImage({
                count: this.maxContractImages - this.customer.contractImages.length,
                sizeType: ['compressed'],
                sourceType: ['album', 'camera'],
                success: (res) => {
                    this.customer.contractImages = [...this.customer.contractImages, ...res.tempFilePaths];
                    if (this.customer.contractImages.length > 0) {
                        delete this.errors.contractImages;
                    }
                }
            });
        },
        
        // 移除合同照片
        removeContractImage(index) {
            this.customer.contractImages.splice(index, 1);
        },
        
        // 提交表单
        async submitForm() {
            if (!this.validateCurrentStep()) {
                return;
            }
            
            try {
                uni.showLoading({
                    title: '提交中...',
                    mask: true
                });
                
                // 准备提交数据
                const formData = {
                    ...this.customer,
                    packageId: this.packageOptions[this.customer.packageIndex].id
                };
                
                // 1. 上传证件照片
                const idImageUrls = await this.uploadImages(formData.idImages, 'id_card');
                
                // 2. 上传合同照片
                const contractImageUrls = await this.uploadImages(formData.contractImages, 'contract');
                
                // 3. 更新表单数据，用上传后的URL替换本地路径
                formData.idImages = idImageUrls;
                formData.contractImages = contractImageUrls;
                
                // 4. 提交数据到服务器
                const result = await this.submitDataToServer(formData);
                
                uni.hideLoading();
                uni.showToast({
                    title: '客户添加成功',
                    icon: 'success'
                });
                
                // 返回上一页
                setTimeout(() => {
                    uni.navigateBack();
                }, 1500);
                
            } catch (error) {
                console.error('提交失败:', error);
                uni.hideLoading();
                uni.showToast({
                    title: '提交失败，请重试',
                    icon: 'none'
                });
            }
        },
        
        // 上传图片
        uploadImages(imagePaths, type) {
            return new Promise((resolve, reject) => {
                if (!imagePaths || imagePaths.length === 0) {
                    resolve([]);
                    return;
                }
                
                const uploadPromises = imagePaths.map((path, index) => {
                    return new Promise((res, rej) => {
                        uni.uploadFile({
                            url: 'https://your-api.com/upload', // 替换为实际的上传API
                            filePath: path,
                            name: 'file',
                            formData: {
                                type: type,
                                index: index
                            },
                            success: (uploadRes) => {
                                if (uploadRes.statusCode === 200) {
                                    const result = JSON.parse(uploadRes.data);
                                    res(result.data.url); // 返回上传后的URL
                                } else {
                                    rej(new Error(`上传失败: ${uploadRes.errMsg}`));
                                }
                            },
                            fail: (err) => {
                                rej(err);
                            }
                        });
                    });
                });
                
                Promise.all(uploadPromises)
                    .then(urls => resolve(urls))
                    .catch(err => reject(err));
            });
        },
        
        // 提交数据到服务器
        submitDataToServer(data) {
            return new Promise((resolve, reject) => {
                // 模拟API请求
                setTimeout(() => {
                    // 实际项目中应使用uni.request发送数据到服务器
                    console.log('提交数据:', data);
                    resolve({ code: 0, message: '成功' });
                }, 1000);
            });
        }
    }
}
</script>

<style>
.container {
    padding: 20rpx;
    background-color: #f5f5f5;
    min-height: 100vh;
	width: 100%;
}

.page-header {
    margin-bottom: 30rpx;
}

.page-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
}

.page-subtitle {
    font-size: 24rpx;
    color: #666;
    margin-top: 6rpx;
}

.form-container {
    background-color: white;
    border-radius: 12rpx;
    padding: 20rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
}

.form-steps {
    display: flex;
    align-items: center;
    margin-bottom: 40rpx;
}

.step-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    flex: 1;
}

.step-number {
    width: 50rpx;
    height: 50rpx;
    border-radius: 50%;
    background-color: #e5e6eb;
    color: #86909c;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    font-weight: bold;
    margin-bottom: 10rpx;
}

.step-text {
    font-size: 24rpx;
    color: #86909c;
}

.step-line {
    flex: 1;
    height: 2rpx;
    background-color: #e5e6eb;
}

.step-item.active .step-number {
    background-color: #165DFF;
    color: white;
}

.step-item.active .step-text {
    color: #165DFF;
}

.step-line.active {
    background-color: #165DFF;
}

.form-step {
    animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(10rpx); }
    to { opacity: 1; transform: translateY(0); }
}

.form-group {
    margin-bottom: 30rpx;
}

.form-label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 15rpx;
    display: flex;
    align-items: center;
}

.required {
    color: #F53F3F;
    margin-left: 6rpx;
}

.form-input-wrapper {
    position: relative;
}

.form-input-wrapper input,
.form-input-wrapper textarea {
    width: 100%;
    padding: 16rpx 20rpx;
    border: 1rpx solid #e5e6eb;
    border-radius: 8rpx;
    font-size: 28rpx;
    color: #333;
}

.form-input-wrapper textarea {
    min-height: 120rpx;
    line-height: 1.5;
}

.form-radio-group {
    display: flex;
    flex-wrap: wrap;
}

.radio-item {
    display: flex;
    align-items: center;
    margin-right: 40rpx;
    margin-bottom: 15rpx;
}

.radio-item radio {
    transform: scale(0.8);
}

.radio-item text {
    font-size: 28rpx;
    color: #333;
    margin-left: 10rpx;
}

.picker {
    width: 100%;
    padding: 16rpx 20rpx;
    border: 1rpx solid #e5e6eb;
    border-radius: 8rpx;
    font-size: 28rpx;
    color: #333;
    background-color: white;
    position: relative;
}

.picker::after {
    content: "\f078";
    font-family: "FontAwesome";
    position: absolute;
    right: 20rpx;
    top: 50%;
    transform: translateY(-50%);
    color: #86909c;
    font-size: 24rpx;
}

.date-separator {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    font-size: 28rpx;
    color: #86909c;
    z-index: 10;
}

.upload-container {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 10rpx;
}

.upload-item {
    position: relative;
    width: 160rpx;
    height: 160rpx;
    margin-right: 20rpx;
    margin-bottom: 20rpx;
}

.upload-preview {
    width: 100%;
    height: 100%;
    border-radius: 8rpx;
    object-fit: cover;
}

.upload-delete {
    position: absolute;
    top: -10rpx;
    right: -10rpx;
    width: 36rpx;
    height: 36rpx;
    background-color: rgba(0, 0, 0, 0.7);
    color: white;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24rpx;
}

.upload-btn {
    width: 160rpx;
    height: 160rpx;
    border: 2rpx dashed #e5e6eb;
    border-radius: 8rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #f8f9fa;
    color: #86909c;
}

.upload-icon {
    font-size: 50rpx;
    margin-bottom: 10rpx;
}

.upload-text {
    font-size: 24rpx;
    text-align: center;
}

.upload-tip {
    font-size: 22rpx;
    color: #86909c;
    margin-top: 10rpx;
}

.error-message {
    font-size: 24rpx;
    color: #F53F3F;
    margin-top: 8rpx;
}

.action-buttons {
    display: flex;
    justify-content: center;
    margin-top: 40rpx;
}

.back-btn,
.next-btn,
.submit-btn {
    width: 280rpx;
    height: 88rpx;
    border-radius: 44rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32rpx;
    margin: 0 20rpx;
}

.back-btn {
    border: 2rpx solid #e5e6eb;
    color: #4e5969;
}

.next-btn,
.submit-btn {
    background-color: #165DFF;
    color: white;
}

.back-btn i,
.next-btn i,
.submit-btn i {
    margin: 0 10rpx;
}
</style>    